package com.simple.spring;

import com.simple.orm.mybatis.Resources;
import com.simple.orm.mybatis.SqlSessionFactory;
import com.simple.orm.mybatis.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

import java.io.Reader;

/**
 * 功能描述:
 *
 * @author: WuChengXing
 * @create: 2021-12-28 15:51
 **/
public class SqlSessionFactoryBean implements FactoryBean<SqlSessionFactory>, InitializingBean {

    private String resource;
    private SqlSessionFactory sqlSessionFactory;

    @Override
    public void afterPropertiesSet() throws Exception {
        // 拿到对应的资源文件，这里是拿到的xml信息，其实也可以拿到yaml的信息去初始化，自己写一套解析yaml的逻辑就行
        try (Reader reader = Resources.getResourceAsReader(resource)) {
            // 这里会去初始化数据库连接，解析sql等操作
            this.sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public SqlSessionFactory getObject() throws Exception {
        return sqlSessionFactory;
    }

    @Override
    public Class<?> getObjectType() {
        return SqlSessionFactory.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }

    public void setResource(String resource) {
        this.resource = resource;
    }
}
